const express = require('express')
const router = express.Router()
const pool = require('../../db/db')
const Response = require('../../utils/ResponseData')

/** 1.首页查询'最新三条日志'接口
 * url: http://localhost:3000/daily/getThree
 */
router.get('/getThree',(req,res,next) => {
    // 按照id排序取最新三条
    const sql = `select * from pet_diary order by d_id desc limit 0,3`
    pool.query(sql,(err,result) => {
        if(err) {
            console.log('/getThree',err);
            next(err)
            return
        }
        if(result.length > 0) {
            res.send(Response.success(result, '日志查询成功！'))

        } else{
            res.send(Response.error('日志查询失败'))
        }
    })
})

/**
 * 查询全部日志接口
 * url: http://localhost:3000/daily/getAll
 */
router.get('/getAll/:page/:pageSize',(req,res,next) => {
    // 获取请求的参数
    let {page,pageSize} = req.params
    let startIndex = (page -1) * pageSize
    pageSize = parseInt(pageSize)
    // 编写sql
    const sql = `select * from pet_diary order by d_id desc limit ?,?`
    pool.querySync(sql,[startIndex,pageSize])
        .then(result => {
            if(result.length > 0) {
                res.send(Response.success(result, '日志查询成功'))
            } else {
                res.send(Response.error('日志查询失败'))
            }
        })
        .catch(err => {
            if(err) {
                console.log(('getAll',err));
                next(err)
                return
            }
        })

})
// 3.通过日志id查询日志接口
router.get('/getById/:id',(req,res,next) => {
    // 按照id排序取最新三条
    const sql = `select * from pet_diary where d_id=?`
    pool.query(sql,[req.params.id],(err,result) => {
        if(err) {
            console.log('/getThree',err);
            next(err)
            return
        }
        if(result.length > 0) {
            res.send(Response.success(result, '日志查询成功！'))

        } else{
            res.send(Response.error('日志查询失败'))
        }
    })
})

module.exports = router